import { getPlanList, queryNearbyShopList } from "@src/api/reservation";

var query;
var rightHeight = 0;
var leftHeight = 0;
var Height;
import { getGoodsBySelf } from "@src/api/mall/good";
import router from "@src/router";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import base from "@src/store/base";
import mall from "@src/store/mall";
import { MALL_RESERVATION_SHELF_ROUTER_PATH } from "@src/common/utils";
import { getStoreDetail } from "@src/api/mall/store";
import location from "@src/store/location";

const ROUTER_PATH = MALL_RESERVATION_SHELF_ROUTER_PATH;
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: base,
      fields: ["themeColor", "themeTitleColor"],
    },
    {
      store: location,
      fields: ["latitude", "longitude"],
      actions: ["getLocation"],
    },
    {
      store: mall,
      fields: ["storeId"],
    },
  ],
  /**
   * 组件的属性列表
   */
  properties: {
    moudlesParam: {
      type: Array,
      value: [],
      observer: function (newVal, oldVal) {
        // 属性值变化时执行
        // console.log("moudlesParam属性值变化时执行=====>", oldVal, newVal);
        if (this.data.storeId) {
          this.setData({
            images: [],
            pageNum: 1,
            noData: false,
          });
          this.getShelfGoodsFunc();
        }
        // console.log("storeId", this.data.storeId);
        // this.getShelfGoodsFunc()
      },
    },
    login: {
      type: Boolean,
    },
    //按高度做瀑布流并且分页
    ifSomePage: {
      type: Boolean,
      value: false,
    },
  },
  options: {
    multipleSlots: true,
    addGlobalClass: true,
  },
  /**
   * 组件的初始数据
   */
  data: {
    omiCPageMsg: "我是data中的omiCPageMsg",
    activeIndex: 0,
    featureList: null,
    pageNum: 1,
    pageSize: 10,
    shelfId: null,
    //商品总数组
    images: null,
    //当前需要加载的数量
    loadingCount: null,
    bizType: null,
    loading: true,
    noData: false,
    goodsList: [],
    nearbyShopList: [],
    storeInfo: {},
  },
  /**
   * 组件生命周期
   */
  lifetimes: {
    created: function (val) {
      // 在组件实例刚刚被创建时执行，注意此时不能调用 setData
    },
    attached: function (val) {
      // console.log("this.data.moudlesParam", this.data.moudlesParam);
      //todo 调试数据，后面删掉
      let tempList = this.data.moudlesParam;
      this.setData({ featureList: tempList });
      this.handleFeatureList();
      if (tempList[0].biz) {
        let params = JSON.parse(tempList[0].biz.params);
        this.setData({
          shelfId: params.shelfId,
          bizType: tempList[0].biz.type,
        });
        this.updateStoreBindings();
        this.getShelfGoodsFunc();
      }
    },
    ready: function (val) {},
    moved: function () {},
    detached: function () {},
  },
  observers: {
    storeId: function (storeId) {
      if (storeId) {
        this.getStoreDetail();
      }
    },
    latitude: function () {
      if (this.data.bizType === "RESERVATION_SHELF") {
        this.queryNearbyShopListReq();
      }
    },
    // longitude: function () {
    //   if (this.data.bizType === "RESERVATION_SHELF") {
    //     this.queryNearbyShopListReq();
    //   }
    // },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    queryNearbyShopListReq() {
      if (!this.data.login) {
        // this.triggerEvent("login");
        return;
      }
      if (this.data.nearbyShopList.length > 0) return;
      let data = {
        latitude: this.data.latitude || "",
        longitude: this.data.longitude || "",
      };
      return queryNearbyShopList(data).then((res) => {
        if (res.code === 0) {
          this.setData({ nearbyShopList: res.data });
          console.log(
            "app-feature获取预约门店列表========================",
            res.data
          );
        }
      });
    },
    getStoreDetail() {
      getStoreDetail({ storeId: this.data.storeId }).then(async (res) => {
        this.setData({ storeInfo: res.data });
        if (this.data.nearbyShopList.length === 0) {
          // await this.queryNearbyShopListReq();
        }
      });
    },
    //跳商品详情页
    jumpPage(e) {
      if (this.data.login) {
        let item = e.currentTarget.dataset.item;
        let urlParams = {
          goodsSerial: item.goodsSerial,
          storeId: this.data.storeId,
        };
        if (this.data.bizType === "RESERVATION_SHELF") {
          const { storeNo } = this.data.storeInfo;
          const nearbyShop =
            this.data.nearbyShopList.filter((v) => v.storeNo === storeNo)[0] ||
            this.data.nearbyShopList[0];
          console.log(
            "app-feature跳转前",
            this.data.nearbyShopList,
            this.data.storeInfo
          );
          urlParams.id = item.planId;
          urlParams.planId = item.planId;
          urlParams.shopId = nearbyShop.shopId || 0;
          urlParams.shopConfigId = nearbyShop.shopConfigId || 0;
        }
        router.push({
          name: ROUTER_PATH[this.data.bizType],
          params: urlParams,
        });
      } else {
        this.triggerEvent("login");
      }
    },
    //feature宽度适配
    handleFeatureList() {
      let featureList = this.data.featureList;
      featureList.forEach((item) => {
        if (item.title) {
          let len = item.title.length;
          if (len == 4) {
            item.width = "150rpx";
          } else if (len == 3) {
            item.width = "100rpx";
          } else if (len == 2) {
            item.width = "85rpx";
          } else {
            item.width = "100rpx";
          }
        }
      });
      this.setData({ featureList });
    },
    //拉取货架商品
    getShelfGoodsFunc() {
      let self = this;
      //todo 测试店铺数据
      let storeId = this.data.storeId;
      let temp = {
        pageNum: this.data.pageNum,
        pageSize: this.data.ifSomePage ? 10 : 50, //最大限制做50条，分页就加载10条
        shelfId: this.data.shelfId,
      };
      /**
       * 第一页 重置成默认数据
       */
      if (this.data.pageNum === 1) {
        this.setData({
          col1: [],
          col2: [],
          col1H: 0,
          col2H: 0,
        });
      }
      const api =
        this.data.bizType === "RESERVATION_SHELF"
          ? getPlanList
          : getGoodsBySelf;
      api(storeId, temp).then((res) => {
        if (res.code === 0) {
          this.setData({
            loadingCount: res.data.list.length,
            images: res.data.list || [],
            pageNum: temp.pageNum + 1,
            goodsList: res.data.list,
          });
          !this.loading &&
            setTimeout(() => {
              this.setData({ loading: false });
            }, 200);
          //没有数据了
          if (!res.data.hasNextPage) {
            this.setData({
              noData: true,
            });
          }
        }
      });
    },
    //点击index,判断处于活跃，并且获取数据
    getindexlist(e) {
      // console.log("e", e);
      if (!this.data.login) {
        this.triggerEvent("login");
        return;
      }
      //判断是否是当前货架
      if (this.data.activeIndex === e.currentTarget.dataset.index) {
        return;
      }
      let item = e.currentTarget.dataset.item;
      if (
        item.biz &&
        (item.biz.type === "MALL_SHELF" ||
          item.biz.type === "RESERVATION_SHELF")
      ) {
        let temp = JSON.parse(item.biz.params);
        this.setData({
          shelfId: temp.shelfId,
          images: [],
          pageNum: 1,
          noData: false,
        });
        this.getShelfGoodsFunc();
      }
      this.setData({
        activeIndex: e.currentTarget.dataset.index,
      });
    },
    onImageLoad: function (e) {
      // let imageId = e.currentTarget.id;
      let imageId = e.currentTarget.dataset.item.goodId;
      let oImgW = e.detail.width; //图片原始宽度
      let oImgH = e.detail.height; //图片原始高度
      // let imgWidth = this.data.imgWidth;  //图片设置的宽度
      let imgWidth = 170; //图片设置的宽度
      let scale = imgWidth / oImgW; //比例计算
      let imgHeight = oImgH * scale; //自适应高度

      let images = this.data.images;
      let loadingCount = this.data.loadingCount;
      images.some((v) => {
        if (v.goodId === imageId) {
          // console.log("imgHeight", imgHeight);
          v.imgHeight = imgHeight >= 530 ? 530 : imgHeight;
          loadingCount--;
          return true;
        }
      });
      this.setData({
        images,
        loadingCount,
      });
      if (loadingCount === 0) {
        this.setColData();
      }
    },
    setColData() {
      let images = this.data.images;
      let col1 = JSON.parse(JSON.stringify(this.data.col1));
      let col2 = JSON.parse(JSON.stringify(this.data.col2));
      images.forEach((v) => {
        if (this.data.col1H <= this.data.col2H) {
          this.data.col1H += v.imgHeight;
          col1.push(v);
        } else {
          this.data.col2H += v.imgHeight;
          col2.push(v);
        }
      });
      this.setData({
        images: [],
        col1,
        col2,
        loadingCount: 0,
      });
    },
    // 图片异常
    onImageError(e) {
      let imageId = e.currentTarget.dataset.item.goodId;
      let images = this.data.images;
      let loadingCount = this.data.loadingCount;
      images.some((v) => {
        if (v.goodId === imageId) {
          // v.cover = "wxapp/static/shop-mall/"
          // v.imgHeight = 170;
          v.cover = "";
          v.imgHeight = 0;
          loadingCount--;
          return true;
        }
      });
      if (loadingCount === 0) {
        this.setColData();
      }
    },
  },
});
